package com.ddm.pay;

import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;

import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.annotation.StyleRes;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;


import com.ddm.pay.R;

import java.lang.ref.WeakReference;


/**
 * 替代diglog 使用dialogFragment, 这是封装的基类
 */

public abstract class BaseDialogFragment<D extends ViewDataBinding> extends DialogFragment {
    private static final String TAG = "base_bottom_dialog";
    private static final float DEFAULT_DIM = 0.2f;
    protected static final int TYPE_TOP = 1;
    protected static final int TYPE_BOTTOM = 2;
    protected static final int TYPE_LEFT = 3;
    protected static final int TYPE_RIGHT = 4;
    protected static final int TYPE_CENTER = 5;
    protected static final int TYPE_NONE = 0;
    protected View mRootView;
    protected D mBinding;
    protected WeakReference<FragmentActivity> mActivity;
    private DialogInterface.OnDismissListener listener;
    private DialogFragmentKeyListener mDialogFragmentKeyListener;
    protected boolean isInit;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(DialogFragment.STYLE_NORMAL, getStyle());

    }

    @StyleRes
    public int getStyle() {
        switch (setDisplayAnimation()) {
            case TYPE_TOP:
                return R.style.BaseDialogUpFragmentStyle;
            case TYPE_BOTTOM:
                return R.style.BaseDialogBottomFragmentStyle;
            case TYPE_LEFT:
                return R.style.BaseDialogLeftFragmentStyle;
            case TYPE_RIGHT:
                return R.style.BaseDialogRightFragmentStyle;
            case TYPE_CENTER:
                return R.style.BaseDialogCenterFragmentStyle;
            default:
                return R.style.BaseDialogFragmentStyle;

        }
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        if (getDialog() != null) {
            getDialog().setCanceledOnTouchOutside(getCancelOutside());
        }
        if (mRootView != null) {
            ViewGroup parent = (ViewGroup) mRootView.getParent();
            if (null != parent) {
                parent.removeView(mRootView);
            }
        } else {
            mRootView = inflater.inflate(getLayoutRes(), container, false);
            mBinding = DataBindingUtil.bind(mRootView);
            initView(getBaseActivity(), mRootView, null);
            initData(getBaseActivity());
            initEvent(getBaseActivity());
        }
        isInit = true;
        onMyCreateView(inflater, container, savedInstanceState);
        getDialog().setOnKeyListener((dialog, keyCode, event) -> {
            if (mDialogFragmentKeyListener != null) {
                return mDialogFragmentKeyListener.onKey(dialog, keyCode, event);
            }

            return false;
        });

        return mRootView;
    }


    public void onMyCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    }

    public void setDialogFragmentKeyListener(DialogFragmentKeyListener dialogInterface) {
        this.mDialogFragmentKeyListener = dialogInterface;
    }

    public void setOnDismissListener(DialogInterface.OnDismissListener listener) {
        this.listener = listener;
    }


    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        mActivity = new WeakReference<>((FragmentActivity) context);
    }


    @LayoutRes
    public abstract int getLayoutRes();

    /**
     * 是否使dialogFragment全屏
     */
    public boolean isHeightMatchParent() {
        return false;
    }

    @Override
    public void onStart() {
        super.onStart();
        if (getDialog() != null) {
            Log.d("getDialogonStart","onStart");
            Window window = getDialog().getWindow();
            WindowManager.LayoutParams params = window.getAttributes();
            params.dimAmount = getDimAmount();
            params.width = WindowManager.LayoutParams.MATCH_PARENT;
            if (isHeightMatchParent()) {
                params.height = WindowManager.LayoutParams.MATCH_PARENT;
            } else {
                params.height = getHeight() > 0 ? getHeight() : WindowManager.LayoutParams.WRAP_CONTENT;
            }
            params.gravity = getGravity();
            window.setAttributes(params);
        }
    }

    /**
     * 设置dialogFragment具体高度
     */

    public int getHeight() {
        return -1;
    }

    /**
     * 设置dialogFragment的位置
     */

    public int getGravity() {
        return Gravity.BOTTOM;
    }

    /**
     * 设置dialogFragment的背景模糊的透明度
     */
    public float getDimAmount() {
        return DEFAULT_DIM;
    }

    /**
     * 设置dialogFragment是否可以被返回键取消
     */
    public boolean getCancelOutside() {
        return true;
    }

    /**
     * 获取dialogFragment的TAG
     */
    public String getFragmentTag() {
        return TAG;
    }

    /**
     * 设置dialogFragment的出现方式
     */
    public int setDisplayAnimation() {
        return TYPE_BOTTOM;
    }


    /**
     * 显示dialogFragment
     */
    public void show(FragmentManager fragmentManager) {
        FragmentTransaction ft = fragmentManager.beginTransaction();
        ft.add(this, TAG);
        ft.commitAllowingStateLoss();
    }

    /**
     * 显示dialogFragment
     */
    public void show(FragmentManager fragmentManager, String tag) {
        FragmentTransaction ft = fragmentManager.beginTransaction();
        ft.add(this, tag);
        ft.commitAllowingStateLoss();
    }


    @Override
    public void onDismiss(@NonNull DialogInterface dialog) {
        super.onDismiss(dialog);
        if (listener != null)
            listener.onDismiss(dialog);
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }

    @Override
    public void onDestroyView() {
        if (getDialog() != null) {
            getDialog().setDismissMessage(null);
        }
        super.onDestroyView();
    }

    public boolean isShowing() {
        return getDialog() != null
                && getDialog().isShowing();

    }

    @Override
    public void dismiss() {
        dismissAllowingStateLoss();
    }

    public FragmentActivity getBaseActivity() {
        FragmentActivity activity = null;
        if (mActivity != null) {
            activity = mActivity.get();
        }
        if (activity == null) {
            activity = getActivity();
        }
//        if (activity == null)
//            activity = AppActivityManager.getAppActivityManager().currentActivity();
        return activity;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

    }

    abstract void initView(Context context, View rootView, AttributeSet attrs);

    abstract void initData(Context context);

    abstract void initEvent(Context context);

    public interface DialogFragmentKeyListener {
        boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event);
    }
}

